/**
 * 创建默认管理员用户
 */

import mongoose from 'mongoose';
import User, { UserRole, UserStatus } from '../models/User';
import logger from '@utils/logger';

export async function createAdminUser(): Promise<void> {
  try {
    // 检查是否已存在管理员
    const existingAdmin = await User.findOne({ username: 'admin' });

    if (existingAdmin) {
      logger.info('Admin user already exists, skipping creation');
      return;
    }

    // 创建管理员用户
    const adminUser = new User({
      username: 'admin',
      email: 'admin@devops.com',
      password: 'admin123', // 默认密码，生产环境需要修改
      fullName: 'System Administrator',
      role: UserRole.ADMIN,
      status: UserStatus.ACTIVE,
      notifications: {
        email: true,
      },
    });

    await adminUser.save();
    logger.info('Admin user created successfully');
  } catch (error) {
    logger.error('Failed to create admin user:', error as Error);
    throw error;
  }
}

export async function createDemoUsers(): Promise<void> {
  try {
    // 检查是否已存在演示用户
    const existingOps = await User.findOne({ username: 'ops_engineer' });

    if (existingOps) {
      logger.info('Demo users already exist, skipping creation');
      return;
    }

    // 创建运维工程师用户
    const opsUser = new User({
      username: 'ops_engineer',
      email: 'ops@devops.com',
      password: 'ops123',
      fullName: 'Operations Engineer',
      role: UserRole.OPS,
      status: UserStatus.ACTIVE,
      notifications: {
        email: true,
      },
    });

    // 创建只读用户
    const viewerUser = new User({
      username: 'viewer',
      email: 'viewer@devops.com',
      password: 'viewer123',
      fullName: 'Viewer User',
      role: UserRole.VIEWER,
      status: UserStatus.ACTIVE,
      notifications: {
        email: false,
      },
    });

    await Promise.all([opsUser.save(), viewerUser.save()]);

    logger.info('Demo users created successfully');
  } catch (error) {
    logger.error('Failed to create demo users:', error as Error);
    throw error;
  }
}

/**
 * 运行种子数据
 */
export async function seedUsers(): Promise<void> {
  await createAdminUser();
  await createDemoUsers();
}
